package algorithms;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lizen
 */
public class FruitIntoBasket {

    public static void test() {
        int [][] fruitsDupArray =  new int[][]{
                {1,2,1},
                {0,1,2,2},
                {1,2,3,2,2}
        };

        Arrays.stream(fruitsDupArray).map(FruitIntoBasket::totalFruits).forEach(System.out::println);
    }

    private static int totalFruits(int[] fruits) {
        int treesLength = fruits.length;
        Map<Integer, Integer> slideWindowMap = new HashMap<>();

        int left = 0, maxPickTrees = 0;
        for (int right = 0; right < treesLength; ++right) {
            slideWindowMap.put(fruits[right], slideWindowMap.getOrDefault(fruits[right], 0) + 1);

            while (slideWindowMap.size() > 2) {
                slideWindowMap.put(fruits[left], slideWindowMap.getOrDefault(fruits[left], 0) - 1);

                if (slideWindowMap.get(fruits[left]) == 0) {
                    slideWindowMap.remove(fruits[left]);
                }
                ++left;
            }

            maxPickTrees = Math.max(maxPickTrees, right - left + 1);
        }

        return maxPickTrees;
    }
}
